import string
import random
import tkinter as tk
import numpy as np
import cv2 as cv

root = tk.Tk()
screen_width = int(root.winfo_screenwidth() * 0.8)
screen_height = int(root.winfo_screenheight() * 0.8)
print(f"屏幕分辨率：{screen_width} x {screen_height}")

img = np.zeros(( screen_height,screen_width,3), np.uint8)
img[:] = (0,255,255) #设置背景为黄色
# cv.imshow("image", img)
# cv.waitKey(0)
cv.imwrite("../img/yellow.jpg", img)
# cv.destroyAllWindows()



mode = True # 如果 True，画矩形，按下‘m’切换到圆形

# 鼠标回调函数
def draw(event,x,y,flags,param):
    if event == cv.EVENT_RBUTTONDBLCLK:
        if mode:
            if(x-50>=0 and y-50>=0 and x+50<=temp.shape[1] and y+50<=temp.shape[0]):
                cv.rectangle(image, (x-50, y-50), (x+50, y+50), (255, 0, 0), -1)
        else:
            if(x-50>=0 and y-50>=0 and x+50<=temp.shape[1] and y+50<=temp.shape[0]):
                cv.circle(image,(x,y),50,(255,0,0),-1)

# image = np.zeros((512,512,3), np.uint8)
temp = cv.imread('../img/yellow.jpg')
image = temp.copy();

cv.namedWindow('image')
cv.setMouseCallback('image',draw)
#随机生成英文名称
imageName = ''.join(random.sample(string.ascii_letters + string.digits, 10)) + ".jpg"

while(1):
    cv.imshow('image', image)
    k = cv.waitKey(1) & 0xFF
    if k == ord('m'):
        mode = not mode
    elif k == ord("s"):
        cv.imwrite("../img/"+imageName,image)
        print("Save image successfully!")
        break
cv.destroyAllWindows()

# 读取画好的图像
image2 = cv.imread('../img/'+imageName)
# cv.imshow('image2', image2)


# 二值化图像
gray = cv.cvtColor(image2, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(gray, 127, 255, 0)

cv.imshow('gray', gray)
cv.waitKey(0)
cv.destroyWindow('gray')
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)


# 查找轮廓
#contours, _ = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
#contours, _ = cv.findContours(image2, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

# 区域计数器
region_count = 0

# 遍历所有轮廓
for contour in contours:
    # 绘制轮廓
    # cv.drawContours(output, [contour], -1, (0,0,255), 1)
    cv.drawContours(image2, contours, -1, (0, 0, 255), 3)

    # 计算轮廓的边界框
    x, y, w, h = cv.boundingRect(contour)

    if x >= 0 and y >= 0 and x + w <= image2.shape[1] and y + h <= image2.shape[0]:
        # 在边界框的左上角标记区域编号
        cv.putText(image2, str(region_count + 1), (x+40, y+55), cv.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)
        region_count += 1
cv.putText(image2, f'Number of regions: {region_count}', (2, 1060), cv.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)
# 显示结果
while True:
    cv.imshow('final result', image2)
    if cv.waitKey(20) & 0xFF == 27:
        break

cv.destroyAllWindows()

#删除图片
import os
os.remove('../img/'+imageName)

# # 打印区域数量
# print(f'Number of regions: {region_count}')
